import React from 'react';
import { connect } from 'dva/index';
import { Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message, Steps } from 'antd';
import { download } from '../../utils/commons'
import OperatorConstant from "../../utils/OperatorConstant";
import Constants from '../../utils/Constants';
import BizParams from '../../components/commons/BizParams'
const { TextArea } = Input;
const Step = Steps.Step;
const Dragger = Upload.Dragger;
const R = require('ramda');
import moment from 'moment'
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;

const invoiceDetail = Form.create({ wrappedComponentRef: true })(class InvoiceDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            disabled: true,
            operate: null //1.做开票资料2.收票3.验票
        }
    }

    handleOpen = (disabled, operate) => {
        this.setState({ open: true, disabled, operate })
    }

    generateInvoice = () => {
        let flag = false;
        this.props.tax.dataSource.products.map(
            item => {
                if (!item.zzrate || !item.taxrate) {
                    flag = true;
                }
            }
        )
        if (flag) { message.info("增值税率或者退税率不能为空！"); return; }
        this.props.dispatch({
            type: 'tax/doInvoice',
            payload: {
                products: this.props.tax.dataSource.products,
                onSuccess: () => {
                    this.setState({ open: false });
                    if (this.props.refreshList) this.props.refreshList();
                    download(apiPath.zbtie + "/api/tax/exportInvoice", { orderId: this.props.tax.dataSource.order.id });
                }
            }
        });
    }

    recInvoice = (openInvoiceStatus) => {
        let flag = false;
        this.props.tax.dataSource.invoiceItems.map(
            item => {
                if (!item.amt) {
                    flag = true;
                }
            }
        )
        if (flag) { message.info("发票金额不能为空！"); return; }
        this.props.dispatch({
            type: 'tax/recInvoice',
            payload: {
                invoiceItems: this.props.tax.dataSource.invoiceItems,
                openInvoiceStatus,
                onSuccess: () => {
                    this.setState({ open: false });
                    if (this.props.refreshList) this.props.refreshList();
                }
            }
        });
    }

    checkin = () => {
        let openinvoicestatus = this.props.form.getFieldValue('checkStatus');
        if (!openinvoicestatus) { message.info("认证结果不能为空！"); return; }
        let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
        let order = dataSource.order ? dataSource.order : {};
        this.props.dispatch({
            type: 'tax/updateOrder',
            payload: {
                id: order.id,
                openinvoicestatus,
                onSuccess: () => {
                    this.handleCancel();
                    if (this.props.refreshList) this.props.refreshList();
                }
            }
        });
    }

    handleCancel = () => {
        this.setState({ open: false })
        this.props.dispatch({
            type: 'tax/refreshState',
            payload: {
                dataSource: {}
            }
        });
    }

    addInvoiceItem = () => {
        let receiptno = this.props.form.getFieldValue("receiptno");//起始编号
        if (!receiptno) { message.error("请输入起始编号"); return; }
        let num = this.props.form.getFieldValue("num");//份数
        if (!num) { message.error("请输入份数"); return; }
        let providerId = this.props.form.getFieldValue("drawername");//选中的供应商
        if (!providerId) { message.error("请选择供应商"); return; }
        let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
        let invoiceItems = dataSource.invoiceItems ? dataSource.invoiceItems : [];
        let providers = dataSource.providers ? dataSource.providers : [];
        let order = dataSource.order ? dataSource.order : {};
        let flag = false;
        let drawername = "";
        invoiceItems.map(item => {
            //判断新录入的发票号是否重复
            for (let i = receiptno; i < receiptno + num; i++) {
                if (item.receiptno == i) flag = true;
            }
        })
        if (flag) { message.error("发票号码重复，请重新输入"); return; }
        providers.map(item => { if (item.id == providerId) drawername = item.name });
        let newAddItems = [];
        for (let i = receiptno; i < receiptno + num; i++) {
            newAddItems.push({ receiptno: i, drawername, orderid: order.id, createtime: moment().format(Constants.DATEFORMAT) });
        }
        dataSource.invoiceItems = invoiceItems.concat(newAddItems);
        this.props.dispatch({ type: 'tax/refreshState', payload: { dataSource } });
    }

    deleteInvoiceItem = (target) => {
        let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
        let invoiceItems = dataSource.invoiceItems ? dataSource.invoiceItems : [];
        dataSource.invoiceItems.splice(invoiceItems.findIndex(item => item.receiptno === target.receiptno), 1);
        this.props.dispatch({ type: 'tax/refreshState', payload: { dataSource } });
    }

    onChangeInvoiceItemAmt = (receiptno, amt) => {
        let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
        let invoiceItems = dataSource.invoiceItems ? dataSource.invoiceItems : [];
        invoiceItems.map(item => {
            if (item.receiptno === receiptno) item.amt = amt
        })
        this.props.dispatch({ type: 'tax/refreshState', payload: { dataSource } });
    }

    columns = [
        { title: '序号', dataIndex: 'id', key: 'id', },
        { title: '税局HSCode', dataIndex: 'hscode', key: 'hscode', },
        { title: '品名', dataIndex: 'name', key: 'name' },
        { title: '品牌', dataIndex: 'branch', key: 'branch', },
        { title: '规格', dataIndex: 'size', key: 'size', },
        {
            title: '型号', key: 'model', render: (text, record, index) => {
                let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
                let order = dataSource.order ? dataSource.order : {};
                if ((order.openinvoicestatus == "1" || order.openinvoicestatus == "2") && (this.state.operate === '1' || this.state.operate === '2')) {
                    return (
                        <Input onChange={(values) => {
                            record.model = values.target.value;
                        }} defaultValue={record.model} style={{ width: 100 }} disabled={this.state.disabled} maxLength="200"/>
                    );
                } else {
                    return (
                        record.model
                    );
                }

            }
        },
        {
            title: '发票备注', key: 'invoiceRemark', render: (text, record, index) => {
                let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
                let order = dataSource.order ? dataSource.order : {};
                if ((order.openinvoicestatus == "1" || order.openinvoicestatus == "2") && (this.state.operate === '1' || this.state.operate === '2')) {
                    return (
                        <Input onChange={(values) => {
                            record.invoiceRemark = values.target.value;
                        }} defaultValue={record.invoiceRemark} style={{ width: 100 }} disabled={this.state.disabled} maxLength="255"/>
                    );
                } else {
                    return (
                        record.invoiceRemark
                    );
                }

            }
        },
        {
            title: '增值税率(%)', dataIndex: 'zzrate', key: 'zzrate', render: (text, record) => {
                let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
                let order = dataSource.order ? dataSource.order : {};
                if ((order.openinvoicestatus == "1" || order.openinvoicestatus == "2") && (this.state.operate === '1' || this.state.operate === '2')
                ) {
                    return (
                        <InputNumber onChange={(value) => {
                            record.zzrate = value;
                        }} defaultValue={record.zzrate} disabled={this.state.disabled} min={0.01} max={100} precision={2} />
                    );
                } else {
                    return (
                        record.zzrate
                    );
                }

            }
        },
        {
            title: '退税率(%)', dataIndex: 'taxrate', key: 'taxrate', render: (text, record) => {
                let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
                let order = dataSource.order ? dataSource.order : {};
                if ((order.openinvoicestatus == "1" || order.openinvoicestatus == "2") && (this.state.operate === '1' || this.state.operate === '2')) {
                    return (
                        <InputNumber onChange={(value) => {
                            record.taxrate = value;
                        }} defaultValue={record.taxrate} disabled={this.state.disabled} min={0.01} max={100} precision={2} />
                    );
                } else {
                    return (
                        record.taxrate
                    );
                }

            }
        },
        { title: '数量', dataIndex: 'number', key: 'number', },
        { title: '单位', dataIndex: 'unit', key: 'unit', },
        { title: '报关单价', dataIndex: 'price', key: 'price', },
        { title: '含税单价', dataIndex: 'costPrice', key: 'costPrice' },
        { title: '含税金额', dataIndex: 'drawerAmount', key: 'drawerAmount', },
        { title: '金额', dataIndex: 'amt', key: 'amt', },
        { title: '税额', dataIndex: 'taxAmt', key: 'taxAmt' },
        { title: '换汇成本', dataIndex: 'costExchange', key: 'costExchange', },
        { title: '供应商名称', dataIndex: 'providerName', key: 'providerName' }
    ];

    columns2 = [
        { title: '发票号码', dataIndex: 'receiptno', key: 'receiptno' },
        { title: '开票人名称', dataIndex: 'drawername', key: 'drawername', },
        {
            title: '金额(人民币)', key: 'amt', render: (text, record, index) => {
                return (
                    <InputNumber onChange={this.onChangeInvoiceItemAmt.bind(this, record.receiptno)} value={record.amt} style={{ width: 100 }} disabled={this.state.disabled || this.state.operate !== '3'} />
                );
            }
        }, {
            title: '录入时间', dataIndex: 'createtime', key: 'createtime',
        }, {
            title: '操作', key: 'key_oprator',
            render: (text, record, index) => {
                let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
                let invoiceItems = dataSource.invoiceItems ? dataSource.invoiceItems : [];
                return (
                    <span style={{ display: this.state.disabled || this.state.operate !== '3' ? 'none' : 'block' }}>
                        <a href="#" onClick={this.deleteInvoiceItem.bind(this, record)}>删除</a>
                    </span>
                );
            }
        }];

    render() {
        const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 } };
        const { getFieldDecorator } = this.props.form;
        let dataSource = this.props.tax.dataSource ? this.props.tax.dataSource : {};
        let order = dataSource.order ? dataSource.order : {};
        let providers = dataSource.providers ? dataSource.providers : [];
        let invoiceItems = dataSource.invoiceItems ? dataSource.invoiceItems : [];
        const footer = [
            <Button style={{ display: this.state.disabled || (this.state.operate !== "1" && this.state.operate !== "2") ? 'none' : 'inline-block' }} key="generateInvoice" size="large" onClick={this.generateInvoice.bind(this, order.id)}>做开票资料</Button>,
            <Button style={{ display: this.state.disabled || this.state.operate !== "3" ? 'none' : 'inline-block' }} key="save" size="large" onClick={this.recInvoice.bind(this, order.openinvoicestatus)}>保存发票</Button>,
            <Button style={{ display: this.state.disabled || this.state.operate !== "3" ? 'none' : 'inline-block' }} key="recInvoice" size="large" onClick={this.recInvoice.bind(this, 4)}>收票</Button>,
            <Button style={{ display: this.state.disabled || this.state.operate !== "4" ? 'none' : 'inline-block' }} key="checkin" size="large" onClick={this.checkin.bind(this)}>提交</Button>,
            <Button key="cancel" size="large" onClick={this.handleCancel.bind(this)}>取消</Button>
        ]

        //统计总数量及总含税金额
        let totalNumer = 0;
        let taotalAmount = 0;
        (dataSource.products ? dataSource.products : []).map(
            item => {
                totalNumer = totalNumer + item.number;
                taotalAmount = taotalAmount + item.drawerAmount;
            }
        )

        console.log(this.state.operate > 2 || (this.state.operate === '2' && this.state.disabled) ? 'block' : 'none');
        
        return (
            <Modal maskClosable={false} visible={this.state.open} width={1100} title={"开票资料"} confirmLoading={this.props.loading} onCancel={this.handleCancel.bind(this)} footer={footer}>
                <Tabs>
                    <TabPane tab="订单信息" key="1">
                        <Form>
                            <Row>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="订单编号" hasFeedback>
                                        {getFieldDecorator('orderno', {
                                            initialValue: order.orderno
                                        })(
                                            <Input disabled={true} />
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="合同协议号" hasFeedback>
                                        {getFieldDecorator('contractno', {
                                            initialValue: order.contractno
                                        })(
                                            <Input disabled={true} />
                                            )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="总费用(含采购成本)" hasFeedback>
                                        {getFieldDecorator('orderno', {
                                            initialValue: dataSource.totalCost
                                        })(
                                            <Input disabled={true} />
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="预估结汇款(请以实际结汇为准)" hasFeedback>
                                        {getFieldDecorator('orderno', {
                                            initialValue: dataSource.totalForex
                                        })(
                                            <Input disabled={true} />
                                            )}
                                    </FormItem>
                                    
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="价格方式" hasFeedback>
                                        {getFieldDecorator('priceclause', {
                                            initialValue: order.priceclause
                                        })(
                                            <BizParams sprCode={"priceItem"} style={{ width: '100%' }} disabled={true} />
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="报关金额" hasFeedback>
                                        {getFieldDecorator('totleamount', {
                                            initialValue: order.totleamount
                                        })(
                                            <Input disabled={true} />
                                            )}
                                    </FormItem>
                                </Col>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="产品总数量" hasFeedback>
                                            {getFieldDecorator('totalNumer', {
                                                initialValue: totalNumer
                                            })(
                                                <Input disabled={true} />
                                                )}
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="总含税金额" hasFeedback>
                                            {getFieldDecorator('taotalAmount', {
                                                initialValue: taotalAmount
                                            })(
                                                <Input disabled={true} />
                                                )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Row>
                        </Form>
                    </TabPane>
                </Tabs>

                <Table rowKey={record => record.id} dataSource={dataSource.products} columns={this.columns} size={'small'} style={{ marginTop: 0 }} scroll={{ x: 1400 }} pagination={false} />
                <Tabs style={{ marginTop: 20, display: this.state.operate > 2 || (this.state.operate === '2' && this.state.disabled) ? 'block' : 'none' }}>
                    <TabPane tab="发票明细" key="1">
                        <Form style={{ marginTop: 20, display: this.state.operate === '3' ? 'block' : 'none' }}>
                            <Row>
                                <Col span={10}>
                                    <FormItem
                                        {...formItemLayout} label="发票号" hasFeedback>
                                        {getFieldDecorator('receiptno', {
                                            rules: [{
                                                required: true, message: '请输入发票号',
                                            }],
                                        })(
                                            <InputNumber style={{ width: 230 }} maxLength="20"/>
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={10}>
                                    <FormItem
                                        {...formItemLayout} label="份数" hasFeedback>
                                        {getFieldDecorator('num', {
                                            rules: [{
                                                required: true, message: '请输入份数',
                                            }],
                                        })(
                                            <InputNumber style={{ width: 230 }} min={1} max={20} />
                                            )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={10}>
                                    <FormItem
                                        {...formItemLayout} label="供应商名称" hasFeedback>
                                        {getFieldDecorator('drawername', {
                                            rules: [{
                                                required: true, message: '请选择供应商名称',
                                            }],
                                        })(
                                            <Select disabled={this.props.disabled} style={{ width: '100%' }}>
                                                {
                                                    providers.map(item => {
                                                        return (<Select.Option value={item.id + ""} key={item.id + ""}>{item.name}</Select.Option>);
                                                    })
                                                }
                                            </Select>
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={10} >
                                    <Button type="primary" icon="search" style={{ marginLeft: 110 }} onClick={this.addInvoiceItem.bind(this)}>新增</Button>
                                </Col>
                            </Row>
                        </Form>
                        <Table rowKey={record => record.receiptno} columns={this.columns2} dataSource={invoiceItems} bordered={true} size={'small'} pagination={false} />
                    </TabPane>
                </Tabs>
                <Tabs style={{ marginTop: 20, display: this.state.operate === '4' && !this.state.disabled ? 'block' : 'none' }}>
                    <TabPane tab="发票认证" key="1">
                        <Form>
                            <Row>
                                <Col span={12}>
                                    <FormItem {...formItemLayout} label="认证结果" hasFeedback>
                                        {getFieldDecorator('checkStatus', {
                                            rules: [{
                                                required: true, message: '请选择认证结果！',
                                            }],
                                            initialValue: ''
                                        })(
                                            <Select style={{ width: 230 }}>
                                                <Select.Option value="5">认证通过</Select.Option>
                                                <Select.Option value="2">认证不通过</Select.Option>
                                            </Select>
                                            )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <FormItem{...formItemLayout} label="备注" hasFeedback>
                                        {getFieldDecorator('memo', {
                                            rules: [{
                                                required: this.state.require_memo, message: '请输入备注！',
                                            }],
                                        })(
                                            <TextArea maxLength="100"/>
                                            )}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </TabPane>
                </Tabs>
            </Modal>
        );
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.tax, tax: state.tax
    };
}

export default connect(mapStateToProps)(invoiceDetail);
